const chokidar = require('chokidar')
const path = require('path')

// E:\web\vscode\project\vue-framework\mock
const mockDir = path.join(process.cwd(), 'mock')

function registerMiddleware (middlewares = []) {
  // 删除node每次缓存的data.js，确保是最新的数据
  delete require.cache[require.resolve('./data.js')]
  const dataArray = require('./data.js')
  dataArray.forEach((item) => {
    middlewares.push({
      // `path` 是可选的
      path: item.url,
      type: item.type,
      middleware: (req, res) => {
        res.send(item.data)
      }
    })
  })
  return middlewares
}

module.exports = (middlewares, devServer) => {
  if (!devServer) {
    throw new Error('webpack-dev-server is not defined')
  }
  const newMiddlewares = registerMiddleware(middlewares)

  chokidar
    .watch(mockDir, {
      ignored: /mock-server/,
      ignoreInitial: true
    })
    .on('all', (event, path) => {
      if (event === 'change' || event === 'add') {
        try {
          // registerMiddleware(newMiddlewares)
          // console.log(require.cache())
        } catch (error) {}
      }
    })

  return newMiddlewares
}
